package pers.john.fsmanager.listener;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import pers.john.fsmanager.command.AbstractCommand;
import pers.john.fsmanager.command.CopyCommand;
import pers.john.fsmanager.command.DeleteCommand;
import pers.john.fsmanager.command.LsCommand;
import pers.john.fsmanager.core.FileManager;
import pers.john.fsmanager.invoker.CommandInvoker;

public class FsListener {
	private FileManager manager;
	private final int PORT = 9000;
	private CommandInvoker invoker;

	public FsListener() {
		manager = new FileManager("public");
		invoker = new CommandInvoker();
	}

	public void listen() throws Exception {
		ServerSocket server = new ServerSocket(PORT);
		System.out.println("文件服务器，启动成功");
		String line = "";
		while (true) {
			Socket socket = server.accept();
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			OutputStream out = socket.getOutputStream();
			
			while (!(line = reader.readLine()).equals("bye")) {
				String[] commandDetail = line.split("\\s+");
				switch (commandDetail[0]) {
				case "ls":
					AbstractCommand command = new LsCommand(out, manager);
					invoker.setCommand(command);
					invoker.invoke();
					break;
				case "cp":
					CopyCommand cpcomand = new CopyCommand(out, manager);
					cpcomand.setSource(commandDetail[1]);
					cpcomand.setTarget(commandDetail[2]);
					invoker.setCommand(cpcomand);
					invoker.invoke();
					break;
				case "rm":
					DeleteCommand dcommand = new DeleteCommand(out, manager);
					dcommand.setSource(commandDetail[1]);
					invoker.setCommand(dcommand);
					invoker.invoke();
					break;

				default:
					out.write("错误的命令\n".getBytes());
					break;
				}
			}
			out.close();
			reader.close();
			socket.close();
		}
	//	server.close();

	}

	public static void main(String[] args) throws Exception {
		new FsListener().listen();
	}
}
